package com.gegao.somethinginteresting.utils.fresco.builder;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.gegao.somethinginteresting.utils.fresco.FRESCOURITYPE;
import com.gegao.somethinginteresting.utils.fresco.FrescoCacheUtils;
import com.gegao.somethinginteresting.utils.fresco.UriUtils;
import com.gegao.somethinginteresting.utils.fresco.callback.FrescoBitmapCallback;
import com.gegao.somethinginteresting.utils.fresco.callback.FrescoClearCompleteCallback;


/**
 * fresco获取图片的构建
 * Created by liuchenghui on 2016/01/06.
 */
public class BitMapGetFrescoRequestBuilder extends FrescoRequestBuilder {

    protected Context mContext;
    protected Handler mHandler;

    public BitMapGetFrescoRequestBuilder(Context context, FrescoBitmapCallback frescoBitmapCallback) {
        this.mContext = context;
        this.mFrescoBitmapCallback = frescoBitmapCallback;
    }


    /**
     * 传入handler让回调在主线程中执行
     *
     * @param handler handler
     */
    public BitMapGetFrescoRequestBuilder runInMainThread(Handler handler) {
        this.mHandler = handler;
        return this;
    }

    @Override
    public void build() {
        if (TextUtils.isEmpty(mUrl))
            return;
        //生成Uri
        Uri uri;
        if (mUrlType == null) {
            mUrlType = FRESCOURITYPE.HTTPURI;
        }
        uri = UriUtils.getUri(mUrl, mUrlType, mPackageName);
        //清除缓存
        if (isClearCache) {
            final Uri finalUri = uri;
            FrescoCacheUtils.clearUriCache(mUrlType, mUrl, mPackageName, new FrescoClearCompleteCallback() {
                @Override
                public void doSomething() {
                    request(finalUri);
                }
            });
        } else {
            request(uri);
        }

    }

    /**
     * 发起加载请求
     */
    private void request(Uri uri) {
        //默认设置
        ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(uri);
        imageRequestBuilder.setAutoRotateEnabled(true)//许多设备会在JPEG文件的metadata中记录下照片的方向,自动匹配图片方向
                .setProgressiveRenderingEnabled(false)//是否支持 图片渐进式加载
                .setLocalThumbnailPreviewsEnabled(false)//如果本地JPEG图，有EXIF的缩略图，image pipeline 会立刻返回一个缩略图。完整的清晰大图，在decode完之后再显示
                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH);//请求经过缓存级别  BITMAP_MEMORY_CACHE，ENCODED_MEMORY_CACHE，DISK_CACHE，FULL_FETCH;
        if (mWidth > 0 && mHeight > 0) {
            imageRequestBuilder.setResizeOptions(new ResizeOptions(mWidth, mHeight));//图片重置的尺寸
        }
        ImageRequest imageRequest = imageRequestBuilder.build();

        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest, mContext);

        DataSubscriber dataSubscriber = new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
            @Override
            public void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

                CloseableReference<CloseableImage> imageReference = dataSource.getResult();
                if (imageReference != null) {
                    try {
                        CloseableStaticBitmap image = (CloseableStaticBitmap) imageReference.get();
                        // do something with the image
                        final Bitmap bitmap = image.getUnderlyingBitmap();
                        if (mHandler != null && Thread.currentThread() != Looper.getMainLooper().getThread()) {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mFrescoBitmapCallback.getBitmap(bitmap);
                                }
                            });
                        } else {
                            mFrescoBitmapCallback.getBitmap(bitmap);
                        }
                    } finally {
                        imageReference.close();
                    }
                }
            }

            @Override
            public void onFailureImpl(DataSource dataSource) {
//                Throwable throwable = dataSource.getFailureCause();
                // handle failure
            }
        };

        dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
    }
}
